package handlers

import (
	"encoding/json"
	"fmt"
	// "time"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 定义一个类型用于处理不同的topic和tag
type TopicHandler func(topic string, payloadData map[string]interface{})

// 全局的映射表，用于根据topic找到对应的处理函数
var topicHandlers = map[string]TopicHandler{}

// 注册topic和对应的处理函数
func RegisterTopicHandler(topic string, handler TopicHandler) {
	topicHandlers[topic] = handler
}

// PublishHandler 处理 MQTT "publish" 事件
func PublishHandler(c *gin.Context) {
	// 获取请求中的 JSON 数据
	var jsonData map[string]interface{}
	if err := c.ShouldBindJSON(&jsonData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 启动 Goroutine 处理发布事件
	go handlePublish(jsonData)

	// 返回响应，防止阻塞
	c.JSON(http.StatusOK, gin.H{"status": "publish event received"})
}

// 通过topic找到对应的处理函数并触发
func handlePublish(data map[string]interface{}) {
	// currentTime := time.Now()
	// fmt.Println(currentTime)
	// fmt.Printf("Handling publish event: %v\n", data)
	// 提取各个字段: clientid, topic, username, payload
	clientID, clientIDExists := data["clientid"].(string)
	topic, topicExists := data["topic"].(string)
	username, usernameExists := data["username"].(string)
	payload, payloadExists := data["payload"].(string)

	if clientIDExists {
		if clientID == "HonokaLaptop" {
			return
		}
		fmt.Printf("Client ID: %s\n", clientID)	
	}
	if topicExists {
		fmt.Printf("Topic: %s\n", topic)
	}
	if usernameExists {
		fmt.Printf("Username: %s\n", username)
	}
	if payloadExists {
		fmt.Printf("Payload: %s\n", payload)
	}

	if handler, exists := topicHandlers[topic]; exists {
		// 尝试解析 payload 中的 JSON 数据
		var payloadData map[string]interface{}
		if err := json.Unmarshal([]byte(payload), &payloadData); err != nil {
			fmt.Printf("非json数据包: %v\n", err)
			return
		}
		// 调用对应的处理函数
		handler(topic, payloadData)
	} else {
		fmt.Printf("未找到匹配的处理函数，topic: %s\n", topic)
	}
}

// 初始化并注册所有的topic处理函数
func InitMQTTModule() {
	RegisterTopicHandler("general/tts", TTSRequestHandler)
	RegisterTopicHandler("general/registration", RegistrationRequestHandler)
}

